

module LPM
  class Process
    attr :pid
    def initialize pid
      @pid = pid
      @pwd = "/proc/#{@pid}"
      raise NoPidExist,"The process which pid is #{@pid} does not exist." unless File.directory? @pwd
    end

    def attr(*arguments)
      h = {}
      begin
        Dir.chdir("#{@pwd}/attr")
        Dir.entries("#{@pwd}/attr").each do |d|
          next if (d == '.') || (d == '..')
          h[d.to_sym] = IO.read("#{@pwd}/attr/#{d}")
        end
      rescue Exception => e
        # => do nothing
        h = "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
      end
      h
    end

    def cwd(*arguments)
      begin
        File.readlink("#{@pwd}/cwd")
      rescue Exception => e
        # => do nothing
        "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
      end
    end

    def exe(*arguments)
      begin
        File.readlink("#{@pwd}/exe")
      rescue Exception => e
        # => do nothing
        "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
      end
    end

    def root(*arguments)
      begin
        File.readlink("#{@pwd}/root")
      rescue Exception => e
        # => do nothing
        "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
      end
    end

    def fd(*arguments)
      r = []
      begin
        Dir.chdir("#{@pwd}/fd")
        Dir.entries("#{@pwd}/fd").each do |d|
          next if (d == '.') || (d == '..')
          if FileTest.symlink?(d)
            r << {d.to_sym => File.readlink(d)}
          else
            r << {d.to_sym => d}
          end
        end
      rescue Exception => e
        # => do nothing
        r = "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
      ensure
        r
      end
    end

    def smaps(*arguments)
      r = []
      begin
        _fd = File.open("#{@pwd}/#{smaps}",'r')
        _ls = _fd.readlines

        while(_ls!=[])
          h = {}
          8.times do
            k,v = _ls.shift.split(/\s*\:\s*/)
            h[k.to_sym] = v
          end
          r << h
        end

      rescue Exception => e
        # => do nothing
        r = "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
      ensure
        _fd.close
      end
      r
    end

    def status(*arguments)
      begin
        _status = IO.read("#{@pwd}/status").split($/)
        h = {}
        _status.each do |line|
          kv = line.split(/\s*\:\s*/)
          h[kv[0].to_sym] = kv[1]
        end
        h
      rescue Exception => e
        # => do nothing
        h = "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
      ensure
      end
    end

    def method_missing(method_name,*args)
      begin
        IO.read("#{@pwd}/#{method_name}")
      rescue Exception => e
        # => do nothing
        "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
      end
    end
  end

	module ClassMethods

	end

	module InstanceMethods

	end

	def self.included(receiver)
		receiver.extend         ClassMethods
		receiver.send :include, InstanceMethods
	end
end
